package com.langsheng.lsintell.ui.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.langsheng.lsintell.R;
import com.langsheng.lsintell.cmd.request.LSRequest;
import com.langsheng.lsintell.config.LSLoginInfos;
import com.langsheng.lsintell.data.LSLoginReq;
import com.langsheng.lsintell.data.LSLoginRes;
import com.langsheng.lsintell.interfaces.LSResDataListener;
import com.langsheng.lsintell.network.LSNet;
import com.langsheng.lsintell.utils.LSUtil;
import com.langsheng.lsintell.utils.LSConst;

/**
 * A login screen that offers login via phone/password.
 */
public class LSLoginActivity extends LSBaseActivity {

    /**
     * Keep track of the login task to ensure we can cancel it if requested.
     */
    // UI references.
    private AutoCompleteTextView mPhoneView;
    private EditText mPasswordView;
    //    private View mProgressView;
    private View mLoginFormView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initTitleView(findViewById(R.id.view_login_title));
        // Set up the login form.
        titleName.setText("登录");
        mPhoneView = (AutoCompleteTextView) findViewById(R.id.phone);
        mPasswordView = (EditText) findViewById(R.id.password);
        mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == R.id.login || id == EditorInfo.IME_NULL) {
                    attemptLogin();
                    return true;
                }
                return false;
            }
        });

        Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
        mEmailSignInButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                attemptLogin();
            }
        });

        mLoginFormView = findViewById(R.id.login_form);
    }

    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid phone, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    private void attemptLogin() {

        // Reset errors.
        mPhoneView.setError(null);
        mPasswordView.setError(null);

        // Store values at the time of the login attempt.
        String phone = mPhoneView.getText().toString();
        String password = mPasswordView.getText().toString();

        boolean cancel = false;
        View focusView = null;

        // Check for a valid password, if the user entered one.
        if (TextUtils.isEmpty(password)) {
            mPasswordView.setError(getString(R.string.error_invalid_password));
            focusView = mPasswordView;
            cancel = true;
        }

        // Check for a valid phone address.
        if (TextUtils.isEmpty(phone)) {
            mPhoneView.setError(getString(R.string.error_invalid_phone));
            focusView = mPhoneView;
            cancel = true;
//        } else if (!LSUtil.isChinaPhoneLegal(phone)) {
//            mPhoneView.setError(getString(R.string.error_invalid_phone));
//            focusView = mPhoneView;
//            cancel = true;
        }

        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            doLogin();
        }
    }

    private void doLogin() {
        LSRequest request = new LSRequest() {
            @Override
            public void createCmd() {
                setCmdCode(0x2008);
                LSLoginReq req = new LSLoginReq();
                req.setMobile(mPhoneView.getText().toString());
//                req.setPassword(LSAES256.encryptPwd(mPasswordView.getText().toString()));
                req.setPassword(LSUtil.getMd5(mPasswordView.getText().toString()));
                req.setEntype("0");
                req.setPushtoken("xxx");
                req.setPlatform(LSConst.PLATFORM_ANDROID);
                setContent(JSONObject.toJSON(req).toString());
            }
        };

        LSNet.getInstance().sendRequest(request, true, new LSResDataListener() {
            @Override
            public boolean onResponse(String content) {
                LSLoginRes result = JSONObject.parseObject(content, LSLoginRes.class);
                LSLoginInfos.getOurInstance().setLoginData(result.getData());
                LSUtil.showToast(LSLoginActivity.this, "登录成功");
                LSLoginActivity.this.finish();
                return false;
            }

            @Override
            public boolean onResponseErr(String errCode, String content) {
                return false;
            }
        });
    }
}

